package org.jeecg.zhenxuan.CommonUtils;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.File;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Properties;

public class VelocityHelper {

	/**
	 *
	 * @param inputFile class path based template file
	 * @throws Exception
	 */
	public static void renderTemplate(String inputFile, HashMap<String, Object> contextMap, Writer output) throws Exception {
		// 初始化并取得Velocity引擎
		VelocityEngine ve = new VelocityEngine();
		Properties p = new Properties();
//		p.setProperty("resource.loader", "class");
//		p.setProperty("class.resource.loader.class",
//				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//		// 设置资源加载器器为ClasspathResourceLoader，这段可以写到配置文件中

		String inputPath = inputFile.substring(0, inputFile.lastIndexOf(File.separator));
		String inputName = inputFile.substring(inputFile.lastIndexOf(File.separator)+File.separator.length());

		p.setProperty("resource.loader", "file");
	    //设置velocity资源加载方式为file时的处理类
	    p.setProperty("file.resource.loader.class",
	    		"org.apache.velocity.runtime.resource.loader.FileResourceLoader");
	    p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, inputPath);

		p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
		p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
		ve.init(p);
		// 取得velocity的模版
		Template t = ve.getTemplate(inputName);
		// 取得velocity的上下文context
		VelocityContext context = new VelocityContext();
		// 把数据填入上下文
		for( Entry<String, Object> item : contextMap.entrySet()){
			context.put(item.getKey(), item.getValue());
		}
		// 转换输出
		t.merge(context, output);
//		ve.evaluate(context, output, "", "template string");
	}

	public static void renderString(String input, HashMap<String, Object> contextMap, Writer output) throws Exception {
		// 初始化并取得Velocity引擎
		VelocityEngine ve = new VelocityEngine();
		ve.init();
		// 取得velocity的上下文context
		VelocityContext context = new VelocityContext();
		// 把数据填入上下文
		for( Entry<String, Object> item : contextMap.entrySet()){
			context.put(item.getKey(), item.getValue());
		}
		// 转换输出
		ve.evaluate(context, output, "", input);
	}


}
